package com.baizhi.service.impl;

import com.baizhi.dao.CmfzArticleDao;
import com.baizhi.entity.CmfzArticle;
import com.baizhi.service.CmfzArticleService;
import com.baizhi.service.LuceneService;
import com.baizhi.util.FileUpload;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/4/9 0009.
 */
@Service
public class CmfzArticleServiceImpl implements CmfzArticleService {
    @Autowired
    private CmfzArticleDao cmfzArticleDao;
    @Autowired
    private LuceneService luceneService;
    private Logger logger= LoggerFactory.getLogger(CmfzArticleServiceImpl.class);


    @Override
    public Map showAll(Integer page, Integer rows, String articleKeywords) throws IOException, InvalidTokenOffsetsException {
        Map map = new HashMap();
        if (articleKeywords != null && !"".equals(articleKeywords)) {

            List<CmfzArticle> cmfzArticles = luceneService.queryByKeyword(articleKeywords);
            List<CmfzArticle> list = new ArrayList<>();

            Integer start = (page-1)*rows;
            Integer end = page*rows-1;
            logger.debug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!page:{}",page);

            if (end <= cmfzArticles.size()-1) {
                for (int i = start; i <= end; i++) {
                    list.add(cmfzArticles.get(i));
                }
            } else {
                start=(cmfzArticles.size()/rows)*rows+1;
                end=cmfzArticles.size()-1;
                for (int i = start; i <= end; i++) {
                    list.add(cmfzArticles.get(i));
                }
            }

            map.put("total", cmfzArticles.size());
            map.put("rows", list);
            return map;
        } else {
            Integer start = (page - 1) * rows;
            List<CmfzArticle> records = cmfzArticleDao.queryAll(start, rows);
            Integer total = cmfzArticleDao.queryCount();

            map.put("total", total);
            map.put("rows", records);

            return map;
        }

    }

    @Override
    public Map add(MultipartFile picture, CmfzArticle cmfzArticle, HttpServletRequest request) {
        Map map = new HashMap();
        try {
            FileUpload.uploadArticlePicture(picture, cmfzArticle, request);
            cmfzArticleDao.add(cmfzArticle);
            map.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("flag", false);
        }
        return map;

    }
}
